package com.jiyiren.demospring.controller;

import com.jiyiren.demospring.bean.UserInfo;
import com.jiyiren.demospring.dao.UserInfoDaoImp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by yiji on 2017/2/22.
 */
@Controller
@RequestMapping("/user")
@SessionAttributes("userinfo")//设置session键
//@SessionAttributes({“attr1”,”attr2”})
public class User {
    private static Log logger= LogFactory.getLog(Hello.class);

    //自动注入
    private UserInfoDaoImp userInfoDaoImp;
    @Autowired
    public User(UserInfoDaoImp userInfoDaoImp) {
        this.userInfoDaoImp=userInfoDaoImp;
    }

    /**
     * 返回登录界面
     * @return
     */
    @GetMapping("/login")
    public String getlogin(@SessionAttribute(value = "userinfo",required = false) UserInfo userInfo){
        if(userInfo!=null&&userInfo.getUserid()!=null){
            return "redirect:/user/"+userInfo.getUserid();
        }
        return "login";
    }

    /**
     * 用户登录
     * @param nameoremail 用户名或者email
     * @param password    密码
     * @param type        登录类型(0为用户名登录/1为email)
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ModelAndView login(@RequestParam String nameoremail, @RequestParam String password,
                              @RequestParam(value = "type",defaultValue = "0") int type){
        ModelAndView modelAndView=new ModelAndView();
        UserInfo userInfo=userInfoDaoImp.getUserInfo(nameoremail,password,type);
        if(userInfo==null){
            modelAndView.setViewName("login");
            modelAndView.addObject("loginerror","Login error！");
            return modelAndView;
        }
        modelAndView.setViewName("redirect:/user/"+userInfo.getUserid());
        modelAndView.addObject("userinfo",userInfo);
        //因为类上设置了sessionAttribute("userinfo"),因此此处的modelAndView存的值将会设置到session中，默认是随单次request而消失的
        logger.info("user:"+userInfo.toString());
        return modelAndView;
    }

    /**
     * 展示用户界面
     * @param userid
     * @param userInfo
     * @return
     */
    @GetMapping("/{userid}")
    public String userPage(@PathVariable("userid") String userid,
                           @SessionAttribute(value = "userinfo",required = false) UserInfo userInfo){
        if(userInfo!=null&&userInfo.getUserid().equals(userid)){
            return "userpage";
        }
        return "redirect:/user/login";
    }



}
